package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;
import com.conversationboard.model.UserProfile;

@WebServlet(name = "ViewUserProfileControllerServlet", urlPatterns = "/ViewUserProfileControllerServlet")
public class ViewUserProfileControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -7565067222738011352L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			String boardId = (String) request.getParameter("boardid");
			String threadId = (String) request.getParameter("threadid");
			String messageId = (String) request.getParameter("messageid");

			int boardIdNumber = Integer.parseInt(boardId);
			int threadIdNumber = Integer.parseInt(threadId);
			int messageIdNumber = Integer.parseInt(messageId);

			String loginId = User.getLoginIdFromMessageId(boardIdNumber, threadIdNumber, messageIdNumber);
			User user = User.get(loginId);

			if (user == null) {
				request.setAttribute("message", "User does not exist in the database.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			UserProfile userProfile = user.getUserProfile();

			request.setAttribute("config", Configuration.getInstance());
			request.setAttribute("user", user);
			request.setAttribute("userProfile", userProfile);

			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/Pages/viewuserprofile.jsp?boardid=" + boardIdNumber + "&amp;threadid=" + threadIdNumber + "&amp;messageid=" + messageIdNumber);
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
